package com.custom.dialogdemo;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;

import com.custom.dialogdemo.dialog.CommonDialog;
import com.custom.dialogdemo.selectcityview.ArrayWheelAdapter;
import com.custom.dialogdemo.selectcityview.CityModel;
import com.custom.dialogdemo.selectcityview.DistrictModel;
import com.custom.dialogdemo.selectcityview.OnWheelChangedListener;
import com.custom.dialogdemo.selectcityview.ProvinceModel;
import com.custom.dialogdemo.selectcityview.WheelView;
import com.custom.dialogdemo.selectcityview.XmlParserHandler;

import org.json.JSONObject;

import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * 选择城市对话框
 * @author yanxs
 *
 */
public class SelectCtiyDialog extends CommonDialog implements View.OnClickListener,OnWheelChangedListener {
	private WheelView mViewProvince;
	private WheelView mViewCity;
	private WheelView mViewDistrict;
	
    public interface OnChangePlatformClick {
        void onPlatformClick(int id);
    }
    
    private OnChangePlatformClick mListener;
    
    private SelectCtiyDialog(Context context, boolean flag, OnCancelListener listener) {
        super(context, flag, listener);
    }
    
	protected int getLayoutId() {
		return R.layout.dialog_selectcity;
	}
    
    @SuppressLint("InflateParams")
    private SelectCtiyDialog(Context context, int defStyle) {
        super(context, defStyle);
        View shareView = getLayoutInflater().inflate(
        		getLayoutId(),null);
        
        shareView.findViewById(R.id.btn_confirm).setOnClickListener(this);
        
		mViewProvince = (WheelView) shareView.findViewById(R.id.id_province);
		mViewCity = (WheelView) shareView.findViewById(R.id.id_city);
		mViewDistrict = (WheelView) shareView.findViewById(R.id.id_district);
		
    	// 添加change事件
    	mViewProvince.addChangingListener(this);
    	// 添加change事件
    	mViewCity.addChangingListener(this);
    	// 添加change事件
    	mViewDistrict.addChangingListener(this);
    	
    	setUpData();
        setContent(shareView, 0);
    }
    
    public SelectCtiyDialog(Context context) {
        this(context, R.style.dialog_bottom);
    }
    
    /**
     * 显示几级	目前最多3级
     * @param ilevel
     */
    public void showLevel(int ilevel){
    	switch (ilevel) {
		case 3:
			mViewDistrict.setVisibility(View.VISIBLE);
			break;
		case 2:
			mViewCity.setVisibility(View.VISIBLE);
			break;
		case 1:
			mViewProvince.setVisibility(View.VISIBLE);
			break;
		default:
			mViewProvince.setVisibility(View.GONE);
			mViewCity.setVisibility(View.GONE);
			mViewDistrict.setVisibility(View.GONE);
			break;
		}
    	
    }
    
    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        getWindow().setGravity(Gravity.BOTTOM);

        WindowManager m = getWindow().getWindowManager();
        Display d = m.getDefaultDisplay();
        WindowManager.LayoutParams p = getWindow().getAttributes();
        p.width = d.getWidth();
        getWindow().setAttributes(p);
    }

    public void setOnPlatformClickListener(OnChangePlatformClick lis) {
        mListener = lis;
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (mListener != null) {
            mListener.onPlatformClick(id);
        }
    }
    
    public String getJsonValue(){
        JSONObject jsonObject = null;
        try {
        	List<String> tempList = Arrays.asList(mDistrictDatasMap.get(mCurrentCityName));
        	if(!tempList.contains(mCurrentDistrictName)){
        		mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[0];
        	}
            jsonObject = new JSONObject();
            jsonObject.put("mCurrentProviceName", mCurrentProviceName);
            jsonObject.put("mCurrentCityName", mCurrentCityName);
            jsonObject.put("mCurrentDistrictName", mCurrentDistrictName);
            jsonObject.put("mCurrentZipCode", mCurrentZipCode);
            
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject == null ? "" : jsonObject.toString();
    }

	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		if (wheel == mViewProvince) {
			updateCities();
		} else if (wheel == mViewCity) {
			updateAreas();
		} else if (wheel == mViewDistrict) {
			mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
			mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
		}
	}
	
	/**
	 * 所有省
	 */
	protected String[] mProvinceDatas;
	/**
	 * key - 省 value - 市
	 */
	protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
	/**
	 * key - 市 values - 区
	 */
	protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();
	
	/**
	 * key - 区 values - 邮编
	 */
	protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>(); 

	/**
	 * 当前省的名称
	 */
	protected String mCurrentProviceName;
	/**
	 * 当前市的名称
	 */
	protected String mCurrentCityName;
	/**
	 * 当前区的名称
	 */
	protected String mCurrentDistrictName ="";
	
	/**
	 * 当前区的邮政编码
	 */
	protected String mCurrentZipCode ="";
	
	/**
	 * 解析省市区的XML数据
	 */
	
    protected void initProvinceDatas()
	{
		List<ProvinceModel> provinceList = null;
    	AssetManager asset = getContext().getAssets();
        try {
            InputStream input = asset.open("province_data.xml");
            // 创建一个解析xml的工厂对象
			SAXParserFactory spf = SAXParserFactory.newInstance();
			// 解析xml
			SAXParser parser = spf.newSAXParser();
			XmlParserHandler handler = new XmlParserHandler();
			parser.parse(input, handler);
			input.close();
			// 获取解析出来的数据
			provinceList = handler.getDataList();
			//*/ 初始化默认选中的省、市、区
			if (provinceList!= null && !provinceList.isEmpty()) {
				mCurrentProviceName = provinceList.get(0).getName();
				List<CityModel> cityList = provinceList.get(0).getCityList();
				if (cityList!= null && !cityList.isEmpty()) {
					mCurrentCityName = cityList.get(0).getName();
					List<DistrictModel> districtList = cityList.get(0).getDistrictList();
					mCurrentDistrictName = districtList.get(0).getName();
					mCurrentZipCode = districtList.get(0).getZipcode();
				}
			}
			//*/
			mProvinceDatas = new String[provinceList.size()];
        	for (int i=0; i< provinceList.size(); i++) {
        		// 遍历所有省的数据
        		mProvinceDatas[i] = provinceList.get(i).getName();
        		List<CityModel> cityList = provinceList.get(i).getCityList();
        		String[] cityNames = new String[cityList.size()];
        		for (int j=0; j< cityList.size(); j++) {
        			// 遍历省下面的所有市的数据
        			cityNames[j] = cityList.get(j).getName();
        			List<DistrictModel> districtList = cityList.get(j).getDistrictList();
        			String[] distrinctNameArray = new String[districtList.size()];
        			DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
        			for (int k=0; k<districtList.size(); k++) {
        				// 遍历市下面所有区/县的数据
        				DistrictModel districtModel = new DistrictModel(districtList.get(k).getName(), districtList.get(k).getZipcode());
        				// 区/县对于的邮编，保存到mZipcodeDatasMap
        				mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
        				distrinctArray[k] = districtModel;
        				distrinctNameArray[k] = districtModel.getName();
        			}
        			// 市-区/县的数据，保存到mDistrictDatasMap
        			mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
        		}
        		// 省-市的数据，保存到mCitisDatasMap
        		mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
        	}
        } catch (Throwable e) {  
            e.printStackTrace();  
        } finally {
        	
        } 
	}
    
    /**
	 * 根据当前的市，更新区WheelView的信息
	 */
	private void updateAreas() {
		int pCurrent = mViewCity.getCurrentItem();
		mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
		String[] areas = mDistrictDatasMap.get(mCurrentCityName);

		if (areas == null) {
			areas = new String[] { "" };
		}
		mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(getContext(), areas));
		mViewDistrict.setCurrentItem(0);
	}

	/**
	 * 根据当前的省，更新市WheelView的信息
	 */
	private void updateCities() {
		int pCurrent = mViewProvince.getCurrentItem();
		mCurrentProviceName = mProvinceDatas[pCurrent];
		String[] cities = mCitisDatasMap.get(mCurrentProviceName);
		if (cities == null) {
			cities = new String[] { "" };
		}
		mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(getContext(), cities));
		mViewCity.setCurrentItem(0);
		updateAreas();
	}
    
	private void setUpData() {
		initProvinceDatas();
		mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(getContext(), mProvinceDatas));
		// 设置可见条目数量
		mViewProvince.setVisibleItems(7);
		mViewCity.setVisibleItems(7);
		mViewDistrict.setVisibleItems(7);
		updateCities();
		updateAreas();
	}
}
